package com.edais.actions;

import com.alibaba.fastjson.JSONObject;
import com.edais.service.InvitationService;
import com.edais.service.UserService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.Message;
import com.edais.util.StringUtil;
import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/invitation")

public class InvitationAction  implements Serializable{
	private static final Log logger = LogFactory.getLog(InvitationAction.class);

	@Autowired
	private InvitationService invitationService;

	@Autowired
	private UserService userService;

	/** 我的邀请码
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/getMyInvitationCd")
	public void getMyInvitationCd(HttpServletRequest request, HttpServletResponse response){
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");   // 用户id

		// 用户id为空
		if (StringUtils.isBlank(userId)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
														Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
														Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			logger.debug("/invitation/getMyInvitationCd 传入参数为空-----userId");
			return;
		}
		
		try {
			// 根据用户id获取我的邀请码
			Map<String, Object> jsonMap = invitationService.getMyInvitationCd(userId);
			
			String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
		} catch (Exception e) {
			logger.debug("/invitation/getMyInvitationCd 获取我的邀请码 异常：" + e.getCause());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
														Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
														Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}
	
	/** 活动文案
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/getActivityRecord")
	public void getActivityRecord(HttpServletRequest request, HttpServletResponse response){


		try {
			if (!RequestUtil.validSign(request)) {
				logger.info("无效签名");
				ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
				return;
			}

			if (!RequestUtil.validToken(request)) {
				logger.info("无效token");
				ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
				return;
			}
			RequestHeader header = RequestUtil.decodeHeader(request);

			// 获取活动文案
			Map<String, Object> jsonMap = invitationService.getActivityRecord(header.userId2String());

			ResultDTO result = new ResultDTO(ResultCode.SUCCESS);
			result.setRecord(jsonMap);
			ResponseUtil.write(response,result);
			
		} catch (Exception e) {
			logger.debug("/invitation/getActivityRecord 获取我的邀请码 异常：",e);
			ResponseUtil.write(response,ResultConstant.FAILED);
		}
	}
	
	/** 邀请列表
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/myInvitationList")
	public void getMyInvitationList(HttpServletRequest request, HttpServletResponse response) throws Exception {

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}

		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}

		Integer current = 1;
		Integer pageSize = 10;

		// 解密请求参数
		RequestHeader header = RequestUtil.decodeHeader(request);
		JSONObject paramsMap = RequestUtil.decodeDataJson(request);
		//Map<String, String> paramsMap = RequestUtil.decodeDataToString(request);
		Long userId = header.getUserId();   // 用户id
		String currentStr = paramsMap.getString(Consts.Page.PAGE_CURRENT_NAME);   //当前页数
		String pageSizeStr = paramsMap.getString(Consts.Page.PAGE_SIZE_NAME);     //页大小
        if(null != currentStr && !("".equals(currentStr))){
            current = Integer.parseInt(currentStr);
        }
        if(null != pageSizeStr && !("".equals(pageSizeStr))){
            pageSize = Integer.parseInt(pageSizeStr);
        }

        // 根据用户id获取我的邀请码
        Map<String, Object> jsonMap = invitationService.getMyInvitationList(String.valueOf(userId), current, pageSize);
        List<?> list = (List<?>) jsonMap.get("list");
        String total = String.valueOf(jsonMap.get("total"));
        ResultDTO result = new ResultDTO<>(ResultCode.SUCCESS);
        // 分页参数
        if (StringUtil.isNotEmpty(total)) {
            result.setTotal(Integer.valueOf(total));
        }
        result.setPageSize(pageSize);
        result.setRecords(list);
        // 处理返回结果
        ResponseUtil.write(response,  result);
    }

	/**
	 * 跳转邀请好友静态页
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getInvitationById")
	public void getInvitationById(HttpServletRequest request,
								  HttpServletResponse response) throws Exception {

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}
		// 解密请求参数
		RequestHeader header = RequestUtil.decodeHeader(request);
		
	//	Map<String, String> paramsMap = RequestUtil.decodeDataToString(request);
		Long userId = header.getUserId();   // 用户id

		Map<String, Object> jsonMap = this.invitationService.getInvitationById(String.valueOf(userId));
        // 处理返回结果
		ResultDTO result = new ResultDTO(ResultCode.SUCCESS);
		result.setRecord(jsonMap);
		ResponseUtil.write(response,result);
	}
}
